package cc.rboot.inject.interceptor;

import cc.rboot.inject.core.IMapperInjector;
import cc.rboot.inject.core.InjectConstant;
import cc.rboot.inject.core.InjectTokenStore;
import cc.rboot.token.core.IToken;
import cc.rboot.token.core.ITokenAware;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class InjectInterceptor implements HandlerInterceptor {

    private final static String BEST_MATCHING_PATTERN = "org.springframework.web.servlet.HandlerMapping.bestMatchingPattern";

    @Resource
    public ITokenAware tokenProcessor;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = ((HandlerMethod) handler);

        if (handlerMethod.getBean() instanceof IMapperInjector) {
            String bestMatchingPattern = (String) request.getAttribute(BEST_MATCHING_PATTERN);

            Class<? extends IToken> tokenClass = InjectTokenStore.get(request.getMethod() + "_" + bestMatchingPattern);

            if (tokenClass != null) {
                tokenProcessor.require(tokenClass);
            }
            IMapperInjector inject = (IMapperInjector) handlerMethod.getBean();
            request.setAttribute(InjectConstant.INJECT_ENTITY, inject.getService().getEntityClass());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
